<template>
  <div v-if="visible" class="">
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :modal-class="modalClass"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <div ref="searchRef">
        <a-row class="table-search mb-3">
          <a-col :flex="1">
            <a-form
              :model="query"
              layout="inline"
              label-align="left"
            >
              <a-row :gutter="16">
                <a-col flex="220px">
                  <a-input v-model="query.name" placeholder="请输入名称" allow-clear>
                    <template #prepend>名称</template>
                  </a-input>
                </a-col>
                <a-col flex="360px">
                  <a-input-group>
                    <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                      <a-option value="created_at" label="添加时间" />
                    </a-select>
                    <a-range-picker v-model="query.range_date" allow-clear/>
                  </a-input-group>
                </a-col>
                <a-col flex="160px">
                  <a-space :size="5">
                    <a-button type="primary" @click="search"><template #icon><icon-search /></template>搜索</a-button>
                    <a-button @click="refresh()"><template #icon><icon-refresh /></template>重置</a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </div>
      <div ref="tableContainerRef">
        <a-table
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :pagination="pagination"
          :data="renderData"
          :bordered="{ wrapper: true, cell: true }"
          :row-selection="rowSelection"
          :scroll="tableScroll"
          column-resizable
          @selection-change="selectionChange"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #columns>
            <a-table-column title="ID" data-index="id" :sortable="{ sortDirections: ['ascend', 'descend'] }" align="center" fixed="left" :width="60"/>
            <a-table-column title="头像" data-index="username" align="center" :width="70">
              <template #cell="{ record }">
                <a-image v-if="record.full_avatar" :src="record.full_avatar" width="40"/>
              </template>
            </a-table-column>
            <a-table-column title="名称" data-index="name" align="center" :width="160"/>
            <a-table-column title="手机号" data-index="mobile" align="center" :width="120"/>
            <a-table-column title="创建时间" data-index="created_at" :sortable="{ sortDirections: ['ascend', 'descend'] }" align="center" :width="180"/>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
  import { Message } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import useVisible from '@/hooks/visible';
  import tool from '@/utils/tool';
  import { apiList } from '@/api/member';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    ids: {
      type: Array,
      default() {
        return [];
      },
    },
    selectionType: {
      type: String,
      default: 'checkbox',
    },
  });
  const emit = defineEmits(['selectCallback']);

  const { loading, setLoading } = useLoading(true);
  const basePagination = {
    current: 1,
    pageSize: 20,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 50, 100, 150, 200, 300, 500],
  };
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      name: '',
      time_type: 'created_at',
      range_date: [],
    };
  };
  const renderData = ref([]);
  const query = ref(baseQuery());
  const pagination = reactive({
    ...basePagination,
  });
  const selectedIds = computed({
    get() {
      return props.ids;
    },
    set(val) {

    },
  });
  const rowSelection = reactive({
    type: props.selectionType,
    // selectedRowKeys: selectedIds,
    // defaultSelectedRowKeys: selectedIds.value,
    defaultSelectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });
  const modalStyle = {
    width: '60%',
    height: '80%',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };
  const modalClass = `modal-${tool.generateId()}`;

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();

  let selectionKeys = []; // 选中项ID
  let selectionDatas = []; // 选中项
  const { visible, setVisible } = useVisible(false);
  const dialogTitle = ref();

  const settingFixedPage = () => {
    const workHeight = document.querySelector(`.${modalClass}`).offsetHeight - 168;
    const tableHeight = workHeight - searchRef.value.offsetHeight;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    settingFixedPage();
  };

  // 列表
  const fetchData = async (
    params = { ...query.value }
  ) => {
    setLoading(true);
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 分页
  const onPageChange = async (page) => {
    await fetchData({ ...query.value, page });
  };
  const onPageSizeChange = async (limit) => {
    await fetchData({ ...query.value, limit });
  };
  // 表单重置
  const reset = async () => {
    //
  };
  // 搜索
  const search = async () => {
    query.value.page = 1;
    await fetchData({...query.value});
  };
  // 刷新
  const refresh = async () => {
    query.value = baseQuery();
    await fetchData({...query.value});
  };

  // 点击行选择器时触发 -- table 表头
  const select = (rowKeys, rowKey, record) => {
    selectionKeys = rowKeys;
    if (props.selectionType === 'checkbox') {
      if (!rowKeys.includes(rowKey)) {
        selectionDatas.forEach((item, index) => {
          if (index === rowKey) {
            selectionDatas.splice(index, 1);
          }
        });
      } else {
        selectionDatas[rowKey] = record;
      }
    } else {
      selectionDatas[0] = record;
    }
  };
  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys) => {
    selectionKeys = rowKeys;
    selectionDatas = [];
    renderData.value.forEach((record, index) => {
      const rowKey = record.id;
      if (rowKeys.includes(rowKey) && !selectionDatas[rowKey]) {
        if (props.selectionType === 'checkbox') {
          selectionDatas[rowKey] = record;
        } else {
          selectionDatas[0] = record;
        }
      }
    });
  };
  const selectMsg = (message = '') => {
    Message.info(message || '请选择需要操作的数据');
  };

  const dialogCancel = () => {
    setVisible(false);
  };
  const dialogBeforeOk = (done) => {
    if (props.selectionType === 'checkbox') {
      emit('selectCallback', selectionKeys);
    } else {
      emit('selectCallback', selectionDatas[0]);
    }
    done();
  };

  // 初始化
  const initData = async (ids = []) => {
    setVisible(true);
    dialogTitle.value = '用户';
    rowSelection.defaultSelectedRowKeys = ids;

    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    settingFixedPage();
  };

  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
  // 暴露方法【给父级调用】
  defineExpose({
    initData,
  });
</script>

<style scoped lang="less">

</style>
